﻿using ConfExpert.Forms.Base;
using ConfExpert.Utility;
using ConfExpert.Utility.Grid;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Views.BandedGrid;
using DevExpress.XtraGrid.Views.Grid;
using DevTeam;
using DevTeamIT;
using Karbel;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using System.Xml;

namespace Extensions
{
    public static class GridViewExtensions
    {
        public static void SetViewCaption(this GridView gridView, string Caption)
        {
            gridView.OptionsView.ShowViewCaption = true;
            gridView.ViewCaption = Caption;
        }

        public static void ClearColumnEdit(this GridView gridView, string FieldName)
        {
            gridView.Columns[FieldName].ColumnEdit = null;
            gridView.Columns[FieldName].Caption = null;
        }

        public static void Freeze(this GridView gridView, int visibleIndex)
        {
            List<DevExpress.XtraGrid.Columns.GridColumn> cols = new List<DevExpress.XtraGrid.Columns.GridColumn>();
            for (int i = 0; i < visibleIndex + 1; i++)
                cols.Add(gridView.VisibleColumns[i]);

            foreach (var o in cols)
                o.Fixed = DevExpress.XtraGrid.Columns.FixedStyle.Left;
        }




        /// <summary>
        /// 
        /// </summary>
        /// <param name="gridView"></param>
        /// <param name="pairs">OldColumn:NewColumn , OldColumn:NewColumn , ...</param>
        public static void SetCaptions(this GridView gridView, params string[] pairs)
        {
            string problematicCols = string.Empty;
            foreach (string pair in pairs)
            {
                try
                {
                    string[] vals = pair.Split(':');
                    string colName = vals[0].Trim();
                    string caption = vals[1].Trim();
                    gridView.Columns[colName].Caption = caption;
                    if (caption == "#")
                        gridView.Columns[colName].ToolTip = colName;
                }
                catch
                {
                    problematicCols += pair + ",";
                }
            }

            if (problematicCols != string.Empty)
            {
                ApplicationException aex = new ApplicationException("Sütun isimlendirmede hata! Bulunmayan sütun ismi : " + problematicCols.Substring(0, problematicCols.Length - 1));
                LogManager.Notify(aex);
            }
        }

        private static BindingSource GetBS(DataTable dt)
        {
            DataSet dsx = dt.DataSet;
            if (dsx == null)
            {
                dsx = new DataSet();
                dsx.Tables.Add(dt);
            }
            int index = 0;
            for (int i = 0; i < dsx.Tables.Count; i++)
            {
                if (dsx.Tables[i] == dt)
                {
                    index = i;
                    break;
                }
            }
            return GetBS(dsx, index);
        }

        private static BindingSource GetBS(DataSet ds, int tableIndex)
        {
            string tableName = ds.Tables[tableIndex].TableName;
            if (tableName == string.Empty)
                tableName = "table" + tableIndex;
            BindingSource bs = new BindingSource(ds, tableName);
            return bs;
        }

        public static BindingSource Init(this GridView gridView, string SPName, params object[] SPParams)
        {
            DataSet dsx = Session.DataManager.ExecuteDataSet(SPName, SPParams);
            BindingSource bs = GetBS(dsx, 0);
            return SetBs(gridView, bs);
        }

        public static BindingSource InitByQuery(this GridView gridView, string SPName)
        {
            DataTable dt = Session.DataManager.ExecuteDataTableByQuery(SPName);
            BindingSource bs = GetBS(dt);
            return SetBs(gridView, bs);
        }

        public static void SetIdentity(this GridView gridView, string ColumnName)
        {
            DataColumn dc = gridView.DataTable().Columns[ColumnName];
            dc.AutoIncrement = true;
            dc.AutoIncrementSeed = -1;
            dc.AutoIncrementStep = -1;
        }

        public static BindingSource Init(this GridView gridView, DataTable dataTable)
        {
            BindingSource bs = GetBS(dataTable);
            return SetBs(gridView, bs);
        }

        public static void DisableRowDelete(this GridView gridView)
        {
            GridManager gm = GridManager.GetManager(gridView);
            gm.RowDeleteDisabled = true;
            gm.GridMenu = new GridMenu(gm);
        }

        public static void ShowOnlyNonblankColumns(this GridView gridView, bool status = true)
        {
            GridManager gm = GridManager.GetManager(gridView);
            gm.ShowOnlyNonblankColumns = status;
        }

        private static void GrideEkle(this GridView gridView, string name, string expression = null)
        {
            GridColumn col = new GridColumn();
            if (gridView is BandedGridView)
                col = new BandedGridColumn();

            col.FieldName = col.Caption = col.Name = name;
            if (expression != null)
            {
                col.UnboundType = DevExpress.Data.UnboundColumnType.Bound;
                col.UnboundExpression = expression;
            }
            col.Visible = true;
            gridView.Columns.Add(col);
        }

        public static void SutunEkle(this GridView gridView, string name, Type type)
        {
            DataTable dataSource = gridView.DataTable();
            dataSource.Columns.Add(name, type);
            gridView.GrideEkle(name);

            //UpdateSchema(gridView);
        }

        public static void SutunEkle(this GridView gridView, string name, Type type, string expression)
        {
            //SutunEkle(gridView, name, type, expression, 0);
            gridView.SutunEkle(name, type, expression, 0);
        }

        public static void SutunEkle(this GridView gridView, string name, Type type, string expression, int TableIndex)
        {
            if (expression.Contains("{FK}"))
            {
                string FKName = string.Empty;

                if (expression.ToLower().Contains("child"))
                    FKName = gridView.DataTable().ChildRelations[TableIndex].RelationName;
                if (expression.ToLower().Contains("parent"))
                    FKName = gridView.DataTable().ParentRelations[TableIndex].RelationName;

                expression = expression.Replace("{FK}", FKName);
            }

            DataTable dataSource = gridView.DataTable();
            dataSource.Columns.Add(name, type);

            if (expression != string.Empty)
                dataSource.Columns[name].Expression = expression;

            gridView.GrideEkle(name, expression);

        }

        public static void ChangeExpression(this GridView gridView, string columnName, string expression, int TableIndex = 0)
        {
            if (expression.Contains("{FK}"))
            {
                string FKName = string.Empty;

                if (expression.ToLower().Contains("child"))
                    FKName = gridView.DataTable().ChildRelations[TableIndex].RelationName;
                if (expression.ToLower().Contains("parent"))
                    FKName = gridView.DataTable().ParentRelations[TableIndex].RelationName;

                expression = expression.Replace("{FK}", FKName);
            }

            DataTable dataSource = gridView.DataTable();
            try
            {
                dataSource.Columns[columnName].Expression = expression;
                gridView.Columns[columnName].UnboundExpression = expression;
            }
            catch
            {
                ApplicationException aex = new ApplicationException("Sütun expression değiştirmede hata! Bulunmayan sütun ismi : " + columnName);
                LogManager.Notify(aex);
            }
        }

        static XForm x = new XForm();
        private static BindingSource SetBs(GridView gridView, BindingSource bs, bool updateonly = false)
        {
            x.InitGridView(gridView, bs);

            return bs;
        }

        public static BindingSource AddDetailGrid(this GridView gvMaster, GridView gvDetail, string commaSeperatedKeyColumns)
        {
            DataSet dsRoot = null;
            BindingSource bsRoot = (BindingSource)gvMaster.GridControl.DataSource;

            int dtSourceIndex = -1;
            while (true)
            {
                dtSourceIndex++;
                if (dtSourceIndex > 10)
                {
                    //Pratikte 10+ grid birbirine bağlanmış olmamalıdır ;
                    throw new ApplicationException("Binding kullanım hatası !!!");
                }
                if (bsRoot.DataSource.GetType() == typeof(DataSet))
                {
                    dsRoot = (DataSet)bsRoot.DataSource;
                    break;
                }
                else
                {
                    bsRoot = (BindingSource)bsRoot.DataSource;
                }
            }

            DataTable dtMaster = dsRoot.Tables[dtSourceIndex];
            DataTable dtDetail = dsRoot.Tables[dtSourceIndex + 1];

            string[] colNames = commaSeperatedKeyColumns.Split(',');

            List<DataColumn> dcPKs = new List<DataColumn>();
            List<DataColumn> dcFKs = new List<DataColumn>();

            foreach (string colName in colNames)
            {
                string col = colName.Trim();
                dcPKs.Add(dtMaster.Columns[col]);
                dcFKs.Add(dtDetail.Columns[col]);
            }

            string relationName = string.Format("FK_{0}_{1}_{2}", gvMaster.Name, gvDetail.Name, commaSeperatedKeyColumns.Replace(',', '_').Replace(" ", ""));
            DataRelation dr = new DataRelation(relationName, dcPKs.ToArray(), dcFKs.ToArray());

            dtMaster.ChildRelations.Add(dr);

            BindingSource bsMaster = (BindingSource)gvMaster.GridControl.DataSource;
            BindingSource bsDetail = new BindingSource(bsMaster, dr.RelationName);
            BindingSource bs = SetBs(gvDetail, bsDetail);
            foreach (string colName in colNames)
            {
                gvDetail.Columns[colName.Trim()].Visible = false;

                if (colName.Trim() == "ProductId")
                    if (gvDetail.Columns.Contains(gvDetail.Columns["Scan"]))
                        gvDetail.Columns["Scan"].Visible = false;
            }
            return bs;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="gvMaster"></param>
        /// <param name="gvDetail"></param>
        /// <param name="TableIndex">0 bazlı datatable dummy'i</param>
        /// <param name="commaSeperatedKeyColumns"></param>
        /// <returns></returns>
        /// 

        #region RefreshDataSource
        public static void RefreshDataSource(this GridView gridView, DataTable dt, bool ClearOldData = true)
        {
            gridView.BeginUpdate();
            DataSet dsRoot = gridView.Dataset();
            if (ClearOldData)
                dsRoot.Tables[dt.TableName].Clear();

            dsRoot.Tables[dt.TableName].Merge(dt);
            gridView.EndUpdate();
        }

        public static void RefreshDataSource(this GridView gridView, DataSet d, bool ClearOldData = true)
        {
            gridView.BeginUpdate();
            DataSet dsRoot = gridView.Dataset();
            if (ClearOldData)
                dsRoot.Clear();

            dsRoot.Merge(d);
            gridView.EndUpdate();
        }

        public static void RefreshDataSource(this GridView gridView, bool ClearOldData, string SPName, params object[] SPParams)
        {
            DataSet dsNew = Session.DataManager.ExecuteDataSet(SPName, SPParams);
            RefreshDataSource(gridView, dsNew, ClearOldData);
        }

        public static void RefreshDataSource(this GridView gridView, string SPName, params object[] SPParams)
        {
            RefreshDataSource(gridView, true, SPName, SPParams);
        }
        #endregion




        public static BindingSource AddDetailGrid(this GridView gvMaster, GridView gvDetail, int TableIndex, string commaSeperatedKeyColumns)
        {
            DataSet dsRoot = null;
            BindingSource bsRoot = (BindingSource)gvMaster.DataSource;

            int dtSourceIndex = -1;
            while (true)
            {
                dtSourceIndex++;
                if (dtSourceIndex > 10)
                {
                    //Pratikte 10+ grid birbirine bağlanmış olmamalıdır ;
                    throw new ApplicationException("Binding hatası!");
                }
                if (bsRoot.DataSource.GetType() == typeof(DataSet))
                {
                    dsRoot = (DataSet)bsRoot.DataSource;
                    break;
                }
                else
                    bsRoot = (BindingSource)bsRoot.DataSource;
            }

            DataTable dtMaster = dsRoot.Tables[dtSourceIndex];
            DataTable dtDetail = dsRoot.Tables[TableIndex];

            string[] colNames = commaSeperatedKeyColumns.Split(',');

            List<DataColumn> dcPKs = new List<DataColumn>();
            List<DataColumn> dcFKs = new List<DataColumn>();

            foreach (string colName in colNames)
            {
                dcPKs.Add(dtMaster.Columns[colName]);
                dcFKs.Add(dtDetail.Columns[colName]);
            }

            string relationName = string.Format("FK_{0}_{1}_{2}", gvMaster.Name, gvDetail.Name, commaSeperatedKeyColumns.Replace(',', '_'));
            DataRelation dr = new DataRelation(relationName, dcPKs.ToArray(), dcFKs.ToArray());

            dtMaster.ChildRelations.Add(dr);

            BindingSource bsMaster = (BindingSource)gvMaster.DataSource;
            BindingSource bsDetail = new BindingSource(bsMaster, dr.RelationName);
            BindingSource bs = SetBs(gvDetail, bsDetail);
            foreach (string colName in colNames)
                gvDetail.Columns[colName.Trim()].Visible = false;

            return bs;
        }

        public static DataSet Dataset(this GridView gvMaster)
        {
            DataSet dsRoot = null;
            BindingSource bsRoot = (BindingSource)gvMaster.DataSource;

            int dtSourceIndex = -1;
            while (true)
            {
                dtSourceIndex++;
                if (dtSourceIndex > 10)
                {
                    //Pratikte 10 grid birbirine bağlanmış olmamalıdır ;
                    throw new ApplicationException("Binding kullanım hatası !!!");
                }
                if (bsRoot.DataSource.GetType() == typeof(BindingSource))
                    bsRoot = (BindingSource)bsRoot.DataSource;
                else
                {
                    dsRoot = (DataSet)bsRoot.DataSource;
                    return dsRoot;
                }

            }
        }

        public static DataTable DataTable(this GridView gvMaster)
        {
            DataSet dsRoot = null;
            BindingSource bsRoot = (BindingSource)gvMaster.DataSource;

            DataTable dt;

            List<string> GridColumns = new List<string>();
            for (int i = 0; i < gvMaster.Columns.Count; i++)
                GridColumns.Add(gvMaster.Columns[i].FieldName);

            int dtSourceIndex = -1;
            while (true)
            {
                dtSourceIndex++;
                if (dtSourceIndex > 10)
                {
                    //Pratikte 10 grid birbirine bağlanmış olmamalıdır ;
                    throw new ApplicationException("Binding kullanım hatası !!!");
                }
                if (bsRoot.DataSource.GetType() == typeof(DataSet))
                {
                    dsRoot = (DataSet)bsRoot.DataSource;

                    dt = dsRoot.Tables[dtSourceIndex];
                    bool skip = false;

                    for (int i = 0; i < dt.Columns.Count; i++)
                    {
                        DataColumn dc = dt.Columns[i];
                        if (!GridColumns.Contains(dc.ColumnName))
                        {
                            skip = true;
                            break;
                        }
                    }
                    if (skip)
                        continue;
                    else
                        break;
                }
                else
                    bsRoot = (BindingSource)bsRoot.DataSource;
            }

            return dsRoot.Tables[dtSourceIndex];
        }

        public static void VeriyiGuncelle(this GridView gridView, DataTable dt)
        {
            VeriyiGuncelle(gridView, true, dt);
        }


        public static void VeriyiGuncelle(this GridView gridView, bool ClearOldData, DataTable dt)
        {
            DataSet dsRoot = gridView.Dataset();
            if (ClearOldData)
                dsRoot.Tables[dt.TableName].Clear();
            dsRoot.Merge(dt);
            //gridView.BestFitColumns();
        }

        public static void VeriyiGuncelle(this GridView gridView, string SPName, params object[] SPParams)
        {
            VeriyiGuncelle(gridView, true, SPName, SPParams);
        }

        public static void VeriyiGuncelle(this GridView gridView, bool ClearOldData, string SPName, params object[] SPParams)
        {
            DataSet dsRoot = gridView.Dataset();
            if (ClearOldData)
                dsRoot.Clear();

            DataSet dsNew = Session.DataManager.ExecuteDataSet(SPName, SPParams);

            dsRoot.Merge(dsNew);
            //gridView.BestFitColumns();
        }


        public static void EndEdit(this GridView gridView)
        {
            gridView.CloseEditor();
            gridView.UpdateCurrentRow();
        }

        public static DataTable Update(this GridView gridView, string ColumnNames = "", string SourceSqlTableName = "")
        {
            gridView.CloseEditor();
            gridView.UpdateCurrentRow();

            DataTable dtGrid = gridView.DataTable();
            Dictionary<string, string> expressions = new Dictionary<string, string>();
            List<string> columnNames = new List<string>();

            foreach (DataColumn col in dtGrid.Columns)
            {
                if (col.Expression != string.Empty)
                {
                    expressions.Add(col.ColumnName, col.Expression);
                    col.Expression = "";
                }
                else
                    columnNames.Add(col.ColumnName);
            }


            if (SourceSqlTableName == "")
            {
                columnNames.Sort();
                string result = string.Join(",", columnNames.ToArray());
                DataTable tables = Session.DataManager.ExecuteDataTable("GetTableByColumns", result);
                if (tables.Rows.Count > 1)
                    throw new ApplicationException("Veritabanında aynı sütunları içeren birden fazla tablo var. Update komutunda tablo ismi belirtin.");
                else
                    SourceSqlTableName = tables.Rows[0][0].ToString();
            }

            string colNames = string.Empty;

            if (ColumnNames == "")
            {
                colNames = Session.DataManager.ExecuteDataTable("GetColumnsByTable", SourceSqlTableName).Rows[0][0].ToStr();
            }
            else
                colNames = ColumnNames;


            SqlDataAdapter da = new SqlDataAdapter(string.Format("SELECT {0} FROM {1}", colNames, SourceSqlTableName), Session.DataManager.ConnectionString);
            SqlCommandBuilder builder = new SqlCommandBuilder(da);
            builder.QuotePrefix = "[";
            builder.QuoteSuffix = "]";
            builder.SetAllValues = false;

            da.UpdateCommand = builder.GetUpdateCommand(true);
            da.InsertCommand = builder.GetInsertCommand(true);
            da.DeleteCommand = builder.GetUpdateCommand(true);

            //      da.UpdateCommand.Parameters.Remove(da.UpdateCommand.Parameters["@InsertedOn"]);
            //      da.InsertCommand.Parameters.Remove(da.InsertCommand.Parameters["@InsertedOn"]);
            //     da.DeleteCommand.Parameters.Remove(da.DeleteCommand.Parameters["@InsertedOn"]);

            DataTable changes = dtGrid.GetChanges();

            foreach (KeyValuePair<string, string> keys in expressions)
                dtGrid.Columns[keys.Key].Expression = keys.Value;

            da.RowUpdated += da_RowUpdated;
            da.RowUpdating += da_RowUpdating;

            if (changes != null && changes.Rows.Count > 0)
            {
                changes.Columns.Add("NewId", typeof(int));

                gridView.DataTable().AcceptChanges();
                da.Update(changes);
                return changes;
            }
            else
            {
                DataTable dt = new DataTable();
                dt.Columns.Add("NewId", typeof(int));
                return dt;
            }

        }

        static void da_RowUpdating(object sender, SqlRowUpdatingEventArgs e)
        {
            //   throw new NotImplementedException();
            if (e.StatementType == StatementType.Insert)
            {
                e.Command.Parameters.Add("@id", SqlDbType.Int);
                e.Command.Parameters["@id"].Direction = ParameterDirection.Output;
                e.Command.CommandText += ";SET @id = SCOPE_IDENTITY();";
            }

        }

        static void da_RowUpdated(object sender, SqlRowUpdatedEventArgs e)
        {
            if (e.StatementType == StatementType.Insert)
            {
                e.Row["NewId"] = e.Command.Parameters["@id"].Value;
                //SqlCommand cmdNewID = new SqlCommand("SELECT @@IDENTITY",c:\Program Files (x86)\Microsoft.NET\Primary Interop Assemblies\stdole.dll
                //    e.Command.Connection);
                //// Retrieve the Autonumber and store it in the CategoryID column.
                //int newID  = (int)cmdNewID.ExecuteScalar();
                //e.Status = UpdateStatus.SkipCurrentRow;              
            }


            // throw new NotImplementedException();
        }

        public static int Update(this GridView gridView, int tableIndex, string ColumnNames = "", string SourceSqlTableName = "")
        {
            gridView.CloseEditor();
            gridView.UpdateCurrentRow();

            DataTable dtGrid = gridView.Dataset().Tables[tableIndex];
            Dictionary<string, string> expressions = new Dictionary<string, string>();
            List<string> columnNames = new List<string>();

            foreach (DataColumn col in dtGrid.Columns)
            {
                if (col.Expression != string.Empty)
                {
                    expressions.Add(col.ColumnName, col.Expression);
                    col.Expression = "";
                }
                else
                    columnNames.Add(col.ColumnName);
            }


            if (SourceSqlTableName == "")
            {
                columnNames.Sort();
                string result = string.Join(",", columnNames.ToArray());
                DataTable tables = Session.DataManager.ExecuteDataTable("GetTableByColumns", result);
                if (tables.Rows.Count > 1)
                    throw new ApplicationException("Veritabanında aynı sütunları içeren birden fazla tablo var. Update komutunda tablo ismi belirtin.");
                else
                    SourceSqlTableName = tables.Rows[0][0].ToString();
            }

            string colNames = string.Empty;

            if (ColumnNames == "")
                colNames = "*";
            else
                colNames = ColumnNames;


            SqlDataAdapter da = new SqlDataAdapter(string.Format("SELECT {0} FROM {1}", colNames, SourceSqlTableName), Session.DataManager.ConnectionString);
            SqlCommandBuilder builder = new SqlCommandBuilder(da);
            builder.QuotePrefix = "[";
            builder.QuoteSuffix = "]";
            builder.SetAllValues = false;
            da.UpdateCommand = builder.GetUpdateCommand();

            DataTable changes = dtGrid.GetChanges();

            foreach (KeyValuePair<string, string> keys in expressions)
                dtGrid.Columns[keys.Key].Expression = keys.Value;


            if (changes != null && changes.Rows.Count > 0)
            {
                gridView.DataTable().AcceptChanges();
                return da.Update(changes);
            }
            else
                return 0;
        }

        public static DataTable InitFromDB(this GridView gridView, int GridViewId, int Parameter)
        {
            DataTable dt = Session.DataManager.ExecuteDataTable("GM_GetColumnSettings2", Parameter);

            foreach (GridColumn col in gridView.Columns)
                col.Visible = false;

            foreach (DataRow dr in dt.Rows)
            {
                string colName = dr["ColumnName"].ToString();

                if (gridView.Columns[colName] != null)
                    if (dt.Columns.Contains("Visible") && dr["Visible"].ToInt() > 0)
                        if (dt.Columns.Contains("Position") && dr["Position"] != null)
                            gridView.Columns[colName].VisibleIndex = (int)dr["Position"];
            }
            return dt;
        }

        public static void AddSummary(this GridView gridView, params string[] columnNames)
        {
            gridView.OptionsView.ShowFooter = true;
            foreach (GridColumn col in gridView.Columns)
            {
                if (col.Visible == true)
                {
                    col.SummaryItem.SummaryType = DevExpress.Data.SummaryItemType.Count;
                    col.SummaryItem.DisplayFormat = "{0:#,##0} records";
                    break;
                }
            }

            foreach (string columnName in columnNames)
            {
                if (gridView.Columns[columnName] != null)
                {
                    GridColumn gc = gridView.Columns[columnName];

                    gc.SummaryItem.FieldName = columnName;
                    gc.SummaryItem.SummaryType = DevExpress.Data.SummaryItemType.Sum;
                    gc.SummaryItem.DisplayFormat = "{0:#,##0.#}";
                }
            }
        }

        /// <summary>
        /// Seçili (yoksa focused) satır, belirtilen sütundaki değerleri virgül ile birleştirip döndürür.
        /// </summary>
        /// <param name="gridView"></param>
        /// <param name="columnName"></param>
        /// <returns></returns>
        public static string GetSelectedValues(this GridView gridView, string columnName)
        {
            string idxs = "";
            foreach (int rowHandle in gridView.GetSelectedRows())
                if (rowHandle > -1)
                    idxs += gridView.GetRowCellValue(rowHandle, columnName).ToString() + ",";

            if (idxs == "" &&
                DevExpress.XtraGrid.GridControl.NewItemRowHandle != gridView.FocusedRowHandle &&
                DevExpress.XtraGrid.GridControl.AutoFilterRowHandle != gridView.FocusedRowHandle
                )
                idxs += gridView.GetFocusedRowCellValue(columnName).ToString() + ",";

            idxs = idxs.RemoveIfEndsWith(",");

            return idxs;
        }


        public static void MakeColumnInvisible(this GridView gridView, params string[] columnNames)
        {
            string problematicCols = string.Empty;
            if (columnNames.Length == 0)
                foreach (GridColumn gc in gridView.Columns)
                    gc.Visible = false;
            else
                foreach (string columnName in columnNames)
                    try
                    {
                        gridView.Columns[columnName].Visible = false;
                    }
                    catch
                    {
                        problematicCols += columnName + ",";
                    }
            //gridView.BestFitColumns();

            if (problematicCols != string.Empty)
            {
                ApplicationException aex = new ApplicationException("Sütun gizlemede hata! Bulunmayan sütun ismi : " + problematicCols.Substring(0, problematicCols.Length - 1));
                LogManager.Notify(aex);
            }
        }

        public static void MakeColumnVisibleWithCaptions(this GridView gridView, params string[] pairs)
        {
            int i = -1;
            foreach (string pair in pairs)
            {
                i++;
                string[] names = pair.Split(':');
                string colName = names[0];
                string caption = names[1];
                gridView.Columns[colName].VisibleIndex = i;
                gridView.Columns[colName].Caption = caption;
            }
        }

        public static void MakeColumnVisibleWithCaptions(this GridView gridView, List<string> pairs)
        {
            int i = -1;
            foreach (string pair in pairs)
            {
                i++;
                string[] names = pair.Split(':');
                string colName = names[0];
                string caption = names[1];
                gridView.Columns[colName].VisibleIndex = i;
                gridView.Columns[colName].Caption = caption;
            }
        }

        public static void MakeColumnVisible(this GridView gridView, params string[] pairs)
        {
            int i = -1;
            foreach (string pair in pairs)
            {
                gridView.Columns[pair].VisibleIndex = ++i;
                //gridView.Columns[pair].Caption = pair;
            }
        }

        public static void MakeRowSelectable(this GridView gridView)
        {
            //gridView.OptionsSelection.EnableAppearanceFocusedCell = false;
            //gridView.OptionsSelection.EnableAppearanceFocusedRow = true;

            gridView.OptionsSelection.MultiSelectMode = GridMultiSelectMode.RowSelect;  //CheckBoxRowSelect
            gridView.OptionsSelection.MultiSelect = true;
        }

        public static void MakeCompulsory(this GridView gridView, params string[] columnNames)
        {
            string problematicCols = string.Empty;
            foreach (string columnName in columnNames)
            {
                try
                {
                    //gridView.RowCellStyle += new RowCellStyleEventHandler(gvCompulsory_RowCellStyle);
                    gridView.Columns[columnName].AppearanceCell.BackColor = Color.FromName(AppSession.Settings.ZorunluAlanRengi);  // System.Drawing.Color.Gold;                 
                }
                catch
                {
                    problematicCols += columnName + ",";
                }
            }
            //gridView.BestFitColumns();

            if (problematicCols != string.Empty)
            {
                ApplicationException aex = new ApplicationException("Sütun renklendirmede hata! Bulunmayan sütun ismi : " + problematicCols.Substring(0, problematicCols.Length - 1));
                LogManager.Notify(aex);
            }
        }

        public static void MakeReadOnly(this GridView gridView, params string[] ExceptTheseColumns)
        {
            foreach (GridColumn gc in gridView.Columns)
                gc.OptionsColumn.AllowEdit = ExceptTheseColumns.Any(gc.FieldName.Equals);

            //gridView.OptionsBehavior.Editable = false;
        }

        public static void MakeEditable(this GridView gridView, params string[] ExceptTheseColumns)
        {
            foreach (GridColumn gc in gridView.Columns)
                gc.OptionsColumn.AllowEdit = !ExceptTheseColumns.Any(gc.FieldName.Equals);

            //gridView.OptionsBehavior.Editable = true;
        }



        //public static void MakeColumnsReadOnlyExcept(this GridView gridView, params string[] ExceptTheseColumns)
        //{
        //    foreach (GridColumn gc in gridView.Columns)
        //        gc.OptionsColumn.AllowEdit = !ExceptTheseColumns.Any(gc.FieldName.Contains);

        //    //gridView.OptionsBehavior.Editable = false;
        //}


        public static void MakeColumnsReadOnly(this GridView gridView, params string[] Columns)
        {
            foreach (string col in Columns)
                gridView.Columns[col].OptionsColumn.AllowEdit = false;
        }

        public static void FormatAsPercentage(this GridView gridView, params string[] columnNames)
        {
            string problematicCols = string.Empty;

            foreach (string columnName in columnNames)
            {
                try
                {
                    RepositoryItemProgressBar pb = new RepositoryItemProgressBar();
                    pb.ShowTitle = true;
                    pb.PercentView = true;
                    //pb.DisplayFormat.FormatType = DevExpress.Utils.FormatType.Numeric;
                    //pb.DisplayFormat.FormatString = "P2";
                    pb.Maximum = 100;

                    gridView.Columns[columnName].ColumnEdit = pb;
                }
                catch
                {
                    problematicCols += columnName + ",";
                }
            }
            //gridView.BestFitColumns();

            if (problematicCols != string.Empty)
            {
                ApplicationException aex = new ApplicationException("Sütun yüzdelik formatlamada hata! Bulunamayan sütun ismi : " + problematicCols.Substring(0, problematicCols.Length - 1));
                LogManager.LogToDB(aex);
                //LogManager.Notify(aex);
            }
        }

        public static void SetFilterTypeToCheckedList(this GridView gridView, params string[] columnNames)
        {
            string problematicCols = string.Empty;

            foreach (string columnName in columnNames)
            {
                try
                {
                    GridColumn col = gridView.Columns[columnName];
                    col.OptionsFilter.FilterPopupMode = FilterPopupMode.CheckedList;
                    //col.FilterMode = DevExpress.XtraGrid.ColumnFilterMode.Value;
                    //col.OptionsFilter.ImmediateUpdateAutoFilter = true;
                    //col.OptionsFilter.ImmediateUpdatePopupDateFilterOnCheck = DevExpress.Utils.DefaultBoolean.True;
                    //col.OptionsFilter.ImmediateUpdatePopupDateFilterOnDateChange = DevExpress.Utils.DefaultBoolean.True;                    
                }
                catch
                {
                    problematicCols += columnName + ",";
                }
            }
            //gridView.BestFitColumns();

            if (problematicCols != string.Empty)
            {
                ApplicationException aex = new ApplicationException("Checkbox filtresi oluşturmada hata! Bulunmayan sütun ismi : " + problematicCols.Substring(0, problematicCols.Length - 1));
                LogManager.Notify(aex);
            }
        }





        public static void FormatAsDateTime(this GridView gridView, params string[] columnNames)
        {
            string problematicCols = string.Empty;

            foreach (string columnName in columnNames)
            {
                try
                {
                    GridColumn col = gridView.Columns[columnName];
                    col.DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime;
                    col.DisplayFormat.FormatString = "dd.MM.yyyy HH:mm:ss";
                }
                catch
                {
                    problematicCols += columnName + ",";
                }
            }
            //gridView.BestFitColumns();

            if (problematicCols != string.Empty)
            {
                ApplicationException aex = new ApplicationException("Sütun tarih formatlamada hata! Bulunamayan sütun ismi : " + problematicCols.Substring(0, problematicCols.Length - 1));
                LogManager.LogToDB(aex);
                //LogManager.Notify(aex);
            }
        }



        public static void FormatAsDate(this GridView gridView, params string[] columnNames)
        {
            string problematicCols = string.Empty;

            foreach (string columnName in columnNames)
            {
                try
                {
                    GridColumn col = gridView.Columns[columnName];
                    col.DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime;
                    col.DisplayFormat.FormatString = "dd.MM.yyyy";
                }
                catch
                {
                    problematicCols += columnName + ",";
                }
            }
            //gridView.BestFitColumns();

            if (problematicCols != string.Empty)
            {
                ApplicationException aex = new ApplicationException("Sütun tarih formatlamada hata! Bulunamayan sütun ismi : " + problematicCols.Substring(0, problematicCols.Length - 1));
                LogManager.LogToDB(aex);
                //LogManager.Notify(aex);
            }
        }

        public static void YanYanaGetir(this GridView gridView, params string[] pairs)
        {
            foreach (string pair in pairs)
            {
                string[] cols = pair.Split(':');
                gridView.Columns[cols[0]].VisibleIndex = gridView.Columns[cols[1]].VisibleIndex;
            }
        }

        public static void YanYanaGetirCoklu(this GridView gridView, string BaseColumn, params string[] pairs)
        {
            foreach (string pair in pairs)
            {
                string[] cols = pair.Split(':');
                if (gridView.Columns[cols[0]] == null)
                    continue;
                gridView.Columns[cols[0]].VisibleIndex = gridView.Columns[BaseColumn].VisibleIndex;
            }
        }

        public static void YanYanaGetirCoklu(this DevExpress.XtraGrid.Views.BandedGrid.BandedGridView gridView, string BaseColumn, params string[] pairs)
        {
            foreach (string pair in pairs)
            {
                string[] cols = pair.Split(':');
                gridView.Columns[cols[0]].ColVIndex = gridView.Columns[BaseColumn].ColVIndex - 1;
            }
        }

        public static void SetAlternateRowStyle(this GridView gridView, bool Status)
        {
            gridView.OptionsView.EnableAppearanceEvenRow = Status;
            gridView.OptionsView.EnableAppearanceOddRow = false;    // Status;
        }



        public static void FormatAsPercentage(this GridView gridView, int decimalPoints, params string[] columnNames)
        {
            string problematicCols = string.Empty;

            foreach (string columnName in columnNames)
            {
                try
                {
                    GridColumn col = gridView.Columns[columnName];
                    col.DisplayFormat.FormatType = DevExpress.Utils.FormatType.Numeric; ;
                    col.DisplayFormat.FormatString = "P" + decimalPoints.ToString();
                    //col.FilterMode = DevExpress.XtraGrid.ColumnFilterMode.Value;
                }
                catch
                {
                    problematicCols += columnName + ",";
                }
            }
            //gridView.BestFitColumns();

            if (problematicCols != string.Empty)
            {
                ApplicationException aex = new ApplicationException("Sütun yüzdelik formatlamada hata! Bulunamayan sütun ismi : " + problematicCols.Substring(0, problematicCols.Length - 1));
                LogManager.LogToDB(aex);
                //LogManager.Notify(aex);
            }
        }

        public static void FormatAsNumber(this GridView gridView, int decimalPoints, params string[] columnNames)
        {
            string problematicCols = string.Empty;

            foreach (string columnName in columnNames)
            {
                if (gridView.Columns.Contains(gridView.Columns[columnName]))
                {
                    GridColumn col = gridView.Columns[columnName];
                    col.DisplayFormat.FormatType = DevExpress.Utils.FormatType.Numeric;
                    string format = "#,##0.";
                    for (int i = 0; i < decimalPoints; i++)
                        format += "0";

                    if (format.EndsWith("."))
                        format = format.Substring(0, format.Length - 1);
                    col.DisplayFormat.FormatString = format + ";-" + format + "; ";

                    //col.DisplayFormat.FormatString = "{0:n2}";
                    //TODO: col.DisplayFormat.FormatString = "#,##0.0;-#,##0.0;";

                    col.FilterMode = DevExpress.XtraGrid.ColumnFilterMode.Value;

                    //col.DisplayFormat.FormatType = DevExpress.Utils.FormatType.Numeric;
                    //col.DisplayFormat.FormatString = "#,###";
                    //col.FilterMode = DevExpress.XtraGrid.ColumnFilterMode.Value;

                    //col.ColumnEdit = new RepositoryItemCalcEdit();
                    //col.ColumnEdit = RepositoryManager.MaskedNumeric(decimalPoints != 1 ? decimalPoints : 2);
                }
                else
                    problematicCols += columnName + ",";
            }
            //gridView.BestFitColumns();

            if (problematicCols != string.Empty)
            {
                ApplicationException aex = new ApplicationException("Sütun formatlamada hata! Bulunamayan sütun ismi: " + problematicCols.Substring(0, problematicCols.Length - 1));
                LogManager.LogToDB(aex);
                //LogManager.Notify(aex);
            }

        }

        public static void Export(this GridView gridView, string fileName)
        {
            GridUtility gu = new GridUtility(gridView);
            gu.Export("xlsx", fileName);
        }

        public static void Export(this GridView gridView)
        {
            GridUtility gu = new GridUtility(gridView);
            gu.Export("xlsx");
        }

        public static string Serialize(this GridView gridView)
        {
            return gridView.DataTable().Serialize();
        }

        public static string SerializeChanges(this GridView gridView)
        {
            return gridView.DataTable().SerializeChanges();
        }


        public static void BulkCopy(this DataTable table, string destinationTableName)
        {
            // take note of SqlBulkCopyOptions.KeepIdentity , you may or may not want to use this for your situation.  

            using (var bulkCopy = new SqlBulkCopy(Session.DataManager.ConnectionString, SqlBulkCopyOptions.KeepIdentity))
            {
                foreach (DataColumn col in table.Columns)
                    bulkCopy.ColumnMappings.Add(col.ColumnName, col.ColumnName);

                bulkCopy.BulkCopyTimeout = 600;
                bulkCopy.DestinationTableName = destinationTableName;
                bulkCopy.WriteToServer(table);
            }
        }

        public static string Serialize(this DataTable dataTable)
        {
            DataSet dsNew = new DataSet("MyData");
            DataTable dtNew;
            if (dataTable != null)
                dtNew = dataTable.DefaultView.ToTable();
            else
                dtNew = new DataTable();
            dtNew.TableName = "Table";
            dsNew.Tables.Add(dtNew);

            for (int i = dtNew.Columns.Count - 1; i >= 0; i--)
                if (dtNew.Columns[i].DataType == typeof(System.Byte[]))
                    dtNew.Columns.RemoveAt(i);
                else if (dtNew.Columns[i].DataType == typeof(DateTime))
                    dtNew.Columns[i].DateTimeMode = DataSetDateTime.Unspecified;

            using (TextWriter sw = new StringWriter(CultureInfo.InvariantCulture))
            using (XmlTextWriter tw = new DataManager.KarbelXmlWriter(sw))
            {
                dtNew.WriteXml(tw, XmlWriteMode.IgnoreSchema);
                string oldstr = " xmlns=\"http://tempuri.org/MyData.xsd\"";
                return sw.ToString().Replace(oldstr, string.Empty); // Replace("DocumentElement", "MyData");
            }
        }
    }
}